"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : 硬件故障类--network
Case Name   : switchover时，主节点网络链路闪断
Create At   : 2021/08/02
@zou_jialiang0505328126
Description :
    1.主节点网络链路闪断
    2.主备切换
Expect      :
    1.成功
    2.成功
History     :
    Modified: by wx1115623 at 2022/11/7 增加等待时间使故障恢复
    Modified: by wx1115623 at 2023/3/21 待故障结束后再刷新配置文件
"""

import unittest
import time
from yat.test import Node
from testcase.utils.Common import Common
from testcase.utils.Constant import Constant
from testcase.utils.CommonSH import CommonSH
from testcase.utils.CommonSH import RestartDbCluster
from testcase.utils.Logger import Logger
from testcase.utils.ComThread import ComThread


class NetWork(unittest.TestCase):
    nodes_tuple = ('PrimaryDbUser', 'Standby1DbUser', 'Standby2DbUser')

    @RestartDbCluster(*nodes_tuple)
    def setUp(self):
        self.log = Logger()
        self.log.info(
            '---------Opengauss_Reliability_Hardware_Case135:开始执行---------')
        self.primary_root_node = Node(node='PrimaryRoot')
        self.primary_user_node = Node(node='PrimaryDbUser')
        self.com = Common()
        self.constant = Constant()
        self.primary_sh = CommonSH('PrimaryDbUser')
        self.sta1_sh = CommonSH('Standby1DbUser')

        self.log.info("-------------获取网卡名---------------")
        network_card_cmd = 'ifconfig'
        self.log.info(network_card_cmd)
        network_card_result = self.primary_root_node.sh(
            network_card_cmd).result()
        network_card_list = network_card_result.split('\n\n')
        self.log.info(network_card_list)
        self.networkcard = ''
        for network_card_item in network_card_list:
            if self.primary_user_node.db_host in network_card_item:
                self.networkcard = network_card_item.split(':')[0].strip()
                self.log.info(self.networkcard)

        self.hostmsg = self.primary_root_node.sh('hostname;').result()
        self.log.info(f'hostname is {self.hostmsg}')

    def test_main(self):
        try:
            text1 = '----step1: 注入网络链路闪断 expect:成功----'
            self.log.info(text1)
            inject_command = f" rNetLink_flash " \
                f"(repeat,duration,interval,dev) " \
                f"values (50,2,5,{self.networkcard})"
            cfe_thread = ComThread(
                self.com.cfe_inject, args=(self.primary_root_node,
                                           inject_command,))
            cfe_thread.setDaemon(True)
            cfe_thread.start()

            text = '----step2: 主备切换 expect:成功----'
            self.log.info(text)
            switchover_thread = ComThread(
                self.sta1_sh.executeGsctl,
                args=('switchover', self.constant.SWITCH_SUCCESS_MSG, ))
            switchover_thread.setDaemon(True)
            switchover_thread.start()
            time.sleep(1)

            self.log.info("------------获取switchover结果----------------")
            switchover_thread.join(360)
            result = switchover_thread.get_result()
            self.log.info(result)
            self.assertTrue(result, '执行失败' + text)

            self.log.info("---------------获取故障结果--------------")
            cfe_thread.join(360)
            result = cfe_thread.get_result()
            self.log.info(result)
            flg1 = self.constant.cfe_inject_netflash_success_msg \
                in result or 'Determining IP information' in result
            self.assertTrue(flg1, '执行失败' + text1)
        finally:
            self.log.info("--------------等待故障恢复----------")
            time.sleep(350)
            refresh_res = self.sta1_sh.exec_refresh_conf()
            self.assertTrue(refresh_res, '刷新配置文件失败')

    def tearDown(self):
        self.log.info("--------------恢复集群-------------")
        status = self.primary_sh.check_whether_need_switch(self.hostmsg)
        if status:
            switchover_res = self.primary_sh.executeGsctl(
                'switchover', self.constant.SWITCHOVER_SUCCESS_MSG)
            refresh_res = self.primary_sh.exec_refresh_conf()
            self.assertTrue(switchover_res, '恢复集群失败')
            self.assertTrue(refresh_res, '恢复集群失败')
        self.log.info(
            '--------Opengauss_Reliability_Hardware_Case135:执行完成--------')
